import time
from importlib import import_module
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from home.models import *
from home.tools.JWTTools import g
from rest_framework.response import Response
import json
from home.tools.RedisTools import r
class RequestMiddleWare(MiddlewareMixin):


    def process_request(self, request):
        # 先获取用户的token
        token=request.headers.get("token")
        path=request.path
        bailist=["/home/sendmessage/","/home/login/",]
        # "/home/loginView/"
        if(path in bailist):
            print("ffff")

        else:
            #然后查询角色表
            info=g.jwt_decode(token)
            print(info)
            print(path)
            userphone=info.get("phone")
            user=UserModel.objects.filter(phone__exact=userphone).first()
            role=RoleModel.objects.filter(id=user.role.id).first()
            print(role)
            # sourcelist=role.source.all()
            # listpath=[]
            # for i in sourcelist:
            #     listpath.append(i.url)
            # print(listpath)
            interfacelist=r.get_str("user"+str(user.id)+"interface")
            print(interfacelist)
            interfacelist=json.loads(interfacelist)

            print(interfacelist)
            print(path in interfacelist)
            if(path in interfacelist):
                print("继续")
            else:
                return Response({"message":"没有此权限"})
            # 获取到对应的路径，看是否存在此路径，若有，继续，没有跳出

    def process_response(self, request, response):

        return response
